package org.sxm.cloud.result;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

import java.io.Serializable;
import static org.sxm.cloud.result.ApiResultCode.ERROR;
import static org.sxm.cloud.result.ApiResultCode.SUCCESS;

/**
 * @Description: 统一返回参数定义
 * @Author: xmSheng
 * @Date: 2024/1/22
 */

public class ApiResult<T> implements Serializable {
    /**
     * @Fields: serialVersionUID
     */
    private static final long serialVersionUID = -1872688292237147173L;
    private String code = "1";
    private String reqId;
    /**
     * 接口调用失败时的错误消息.
     */
    private String message;
    /**
     * 服务器响应时间
     */
    private String serviceTime = DateUtil.now();


    /**
     * 具体数据. 依接口返回值而定.
     */
    private T data;

    public static <T> ApiResult success() {
        ApiResult result = new ApiResult<T>();
        result.setCode(SUCCESS.getCode());
        result.setMessage(SUCCESS.getMessage());
        return result;
    }

    public static <T> ApiResult success(T t) {
        ApiResult result = new ApiResult<T>(t);
        result.setCode(SUCCESS.getCode());
        result.setMessage(SUCCESS.getMessage());
        return result;
    }

    public static <T> ApiResult error(T t) {
        ApiResult result = new ApiResult<T>(t);
        result.setCode(ERROR.getCode());
        result.setMessage(ERROR.getMessage());
        return result;
    }


    public String getCode() {
        return code;
    }

    public ApiResult() {

    }

    public ApiResult(T t) {
        this.data = t;
    }

    public ApiResult(String code, T t) {
        this.code = code;
        this.data = t;
    }

    /**
     * 判断相应是否业务成功
     *
     * @return
     */
    public boolean isSuccess() {
        return SUCCESS.getCode().equalsIgnoreCase(this.code);
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getReqId() {
        return reqId;
    }

    public void setReqId(String reqId) {
        this.reqId = reqId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getServiceTime() {
        return serviceTime;
    }

    public void setServiceTime(String serviceTime) {
        this.serviceTime = serviceTime;
    }

    public T getData() {
        return data;
    }

    public void setData(T t) {
        this.data = t;
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}
